package com.example.test622.ui.video

import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class VideoViewModel:BaseViewModel<VideoIntent,VideoState>() {
	init {
		viewModelScope.launch {
			intent.consumeAsFlow().collect{
				when(it){
					is VideoIntent.GetVideo->loadVideo(it.id,it.page,it.size)
					is VideoIntent.FollowUser->userFollow(it.uid,it.nid)
				}
			}
		}
	}
	
	private suspend fun userFollow(uid: Int, nid: Int) {
		val t = try {
			val res = service.followUser(uid, nid)
			if(res.code == 0){
				VideoState.FollowSuccess(res)
			}else{
				VideoState.VideoFailed(res.msg)
			}
		}catch (e:Exception){
			VideoState.VideoFailed(e.message?:"")
		}
		state.postValue(t)
	}
	
	private suspend fun loadVideo(id: String, page: Int, size: Int) {
		val s = try {
			val res = service.getSimpleVideo(id, page, size)
			if(res.code == 0){
				VideoState.VideoSuccess(res)
			}else{
				VideoState.VideoFailed(res.msg)
			}
		}catch (e:Exception){
			VideoState.VideoFailed(e.message?:"")
		}
		state.postValue(s)
	}
}